<template>
  <div class="inbound-form" v-loading="loading">
    <div class="page-header"><h2>新增入库</h2></div>

    <el-card shadow="never">
      <h4>基础信息</h4>
      <el-form :model="form" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="入库主题"><el-input v-model="form.inboundSubject" placeholder="请输入入库主题" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库单号"><el-input v-model="form.inboundOrderNumber" disabled placeholder="系统编号" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库类型">
              <el-select v-model="form.inboundType" placeholder="请选择">
                <el-option label="采购入库" value="采购入库" />
                <el-option label="销售退货" value="销售退货" />
                <el-option label="生产入库" value="生产入库" />
                <el-option label="委外加工入库" value="委外加工入库" />
                <el-option label="委外工单入库" value="委外工单入库" />
                <el-option label="生产退料" value="生产退料" />
                <el-option label="其他入库" value="其他入库" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库日期"><el-date-picker v-model="form.inboundDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库"><el-input v-model="form.warehouseName" placeholder="请选择仓库" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库人员"><el-input v-model="form.inboundPersonnelName" placeholder="请选择入库人员" /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注"><el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" style="margin-top: 16px;">
      <div class="card-header">
        <h4>入库明细</h4>
        <div>
          <el-button size="small" @click="addRow">添加</el-button>
          <el-button size="small" @click="removeSelected">移除</el-button>
        </div>
      </div>
      <el-table :data="form.details" border stripe @selection-change="onSelect">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="物品编号" width="160">
          <template #default="{ row }"><el-input v-model="row.itemNumber" /></template>
        </el-table-column>
        <el-table-column label="物品名称" min-width="180">
          <template #default="{ row }"><el-input v-model="row.itemName" /></template>
        </el-table-column>
        <el-table-column label="规格型号" width="120">
          <template #default="{ row }"><el-input v-model="row.specificationModel" /></template>
        </el-table-column>
        <el-table-column label="单位" width="100">
          <template #default="{ row }"><el-input v-model="row.unit" /></template>
        </el-table-column>
        <el-table-column label="品牌" width="120">
          <template #default="{ row }"><el-input v-model="row.brand" /></template>
        </el-table-column>
        <el-table-column label="入库数量" width="120">
          <template #default="{ row }"><el-input-number v-model="row.inboundQuantity" :min="0" /></template>
        </el-table-column>
        <el-table-column label="主单位数量" width="140">
          <template #default="{ row }"><el-input-number v-model="row.mainUnitQuantity" :min="0" /></template>
        </el-table-column>
        <el-table-column label="批次号" width="140">
          <template #default="{ row }"><el-input v-model="row.batchNumber" /></template>
        </el-table-column>
        <el-table-column label="生产日期" width="140">
          <template #default="{ row }"><el-date-picker v-model="row.productionDate" type="date" value-format="YYYY-MM-DD" /></template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="{ row }"><el-input-number v-model="row.amount" :min="0" /></template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ $index }"><el-button link type="danger" @click="removeAt($index)">移除</el-button></template>
        </el-table-column>
      </el-table>
      <div class="summary">
        总量：{{ form.details.reduce((s,i)=>s+(Number(i.inboundQuantity)||0),0) }}
        总金额：{{ form.details.reduce((s,i)=>s+(Number(i.amount)||0),0).toFixed(2) }}
      </div>
    </el-card>

    <div class="footer-actions">
      <el-button @click="goBack">关闭</el-button>
      <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { inboundApi, type InboundDetailDto, type InboundDetailItem } from '@/api/inboundApi'

const router = useRouter()
const loading = ref(false)

const form = ref<InboundDetailDto>({
  id: 0,
  inboundOrderNumber: '系统生成',
  inboundSubject: '',
  inboundType: '采购入库',
  inboundDate: new Date().toISOString().slice(0,10),
  warehouseName: '',
  inboundPersonnelName: '',
  remarks: '',
  details: []
})

onMounted(async () => {
  const id = Number(new URLSearchParams(location.search).get('id') || 0)
  if (id > 0) {
    loading.value = true
    try {
      const res = await inboundApi.getById(id)
      if (res.code === 200) {
        const d = res.data
        form.value = {
          id: d.id,
          inboundOrderNumber: d.inboundOrderNumber,
          inboundSubject: d.inboundSubject,
          inboundType: d.inboundType,
          inboundDate: d.inboundDate,
          warehouseName: d.warehouseName,
          inboundPersonnelName: d.inboundPersonnelName,
          remarks: d.remarks,
          details: d.details || []
        }
      }
    } finally {
      loading.value = false
    }
  }
})

const selected: InboundDetailItem[] = []
const onSelect = (rows: InboundDetailItem[]) => {
  selected.splice(0, selected.length, ...rows)
}
const addRow = () => {
  form.value.details.push({
    sequenceNumber: form.value.details.length + 1,
    itemNumber: '', itemName: '', specificationModel: '', unit: '', brand: '',
    inboundQuantity: 0, mainUnitQuantity: 0, batchNumber: '', productionDate: '', amount: 0
  })
}
const removeSelected = () => {
  form.value.details = form.value.details.filter(r => !selected.includes(r))
}
const removeAt = (idx: number) => {
  form.value.details.splice(idx, 1)
}

const goBack = () => router.push('/InboundList')

const submit = async () => {
  try {
    loading.value = true
    const id = Number(new URLSearchParams(location.search).get('id') || 0)
    
    // 构建正确的API请求数据
    const apiData = {
      inboundSubject: form.value.inboundSubject,
      inboundType: form.value.inboundType,
      inboundDate: form.value.inboundDate,
      warehouseId: 1, // 临时使用默认仓库ID，后续可以改为下拉选择
      remarks: form.value.remarks,
      details: form.value.details.map(d => ({
        sequenceNumber: d.sequenceNumber,
        itemNumber: d.itemNumber,
        itemName: d.itemName,
        specificationModel: d.specificationModel,
        unit: d.unit,
        brand: d.brand,
        inboundQuantity: d.inboundQuantity,
        mainUnitQuantity: d.mainUnitQuantity,
        batchNumber: d.batchNumber,
        productionDate: d.productionDate,
        amount: d.amount
      }))
    }
    
    if (id > 0) {
      const res = await inboundApi.update(id, apiData)
      if (res.code === 200 && res.data) {
        ElMessage.success('更新成功')
        router.push('/InboundList')
        return
      }
      ElMessage.error(res.message || '更新失败')
      return
    }
    const res = await inboundApi.create(apiData)
    if (res.code === 200) {
      ElMessage.success('创建成功')
      router.push('/InboundList')
    } else {
      ElMessage.error(res.message || '创建失败')
    }
  } catch (e:any) {
    ElMessage.error(e.message || '提交失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.inbound-form { padding: 20px; }
.page-header { margin-bottom: 16px; }
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.summary { margin-top: 10px; text-align: right; color: #f56c6c; }
.footer-actions { margin-top: 20px; text-align: center; }
</style> 